package com.luoyuanxiangvip.web.core.aspect;

import com.luoyuanxiangvip.core.entity.BizArticle;
import com.luoyuanxiangvip.core.entity.BizArticleLook;
import com.luoyuanxiangvip.common.holder.RequestHolder;
import com.luoyuanxiangvip.core.service.IBizArticleLookService;
import com.luoyuanxiangvip.core.service.IBizArticleService;
import com.luoyuanxiangvip.common.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 文章查看aop
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/6/8
 */
@Slf4j
@Component
@Aspect
@Order(1)
public class ArticleLookAspects {

    @Resource
    private IBizArticleService iBizArticleService;
    @Resource
    private IBizArticleLookService iBizArticleLookService;

    @Pointcut("execution(* com.luoyuanxiangvip.web.controller.BizArticleController.articleInfo(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void doFore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            String userIp = IpUtil.getRealIp(RequestHolder.getRequest());
            Long articleId = (Long) args[0];
            BizArticle byId = iBizArticleService.getById(articleId);
            if (byId == null) {
                log.warn("{}-该文章不存在！", articleId);
                return;
            }
            BizArticleLook look = new BizArticleLook();
            look.setArticleId(articleId)
                    .setIp(userIp)
                    .setLookTime(new Date())
                    .setCreateTime(new Date())
                    .setUpdateTime(new Date());
            iBizArticleLookService.save(look);
        }
    }
}
